package com.cscec.omega.service;

import com.alibaba.fastjson.JSONObject;
import com.cscec.omega.config.MongoDBHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class UniversalService {

    private static Logger logger = LoggerFactory.getLogger(UniversalService.class);

    @Autowired
    private MongoDBHelper mongoDBHelper;

    @Autowired
    private OSSService ossService;

    /**
     * 保存数据至mongodb
     * @param jsonObject
     */
    @Transactional
    public JSONObject save(JSONObject jsonObject, String collectionName){
        jsonObject.put("create", LocalDateTime.now());
        try {
            jsonObject = mongoDBHelper.save(jsonObject, collectionName);
        } catch (Exception e) {
            logger.error("save error: ", e);
        }
        return jsonObject;
    }

    /**
     * 保存文件至OSS
     * @param file
     */
    @Transactional
    public String save(MultipartFile file, String collectionName) {
        String originalFilename = file.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectKey = collectionName+"_"+System.currentTimeMillis()+fileType;
        try {
            ossService.upload(objectKey, file.getInputStream());
        } catch (IOException e) {
            logger.error("upload file error: ", e);
            objectKey = "";
        }
        return objectKey;
    }

    /**
     * 保存文件和数据
     * @param file
     * @param jsonObject
     * @param collectionName
     * @return
     */
    @Transactional
    public JSONObject save(MultipartFile file, JSONObject jsonObject, String collectionName) {
        String objectKey = this.save(file, collectionName);
        jsonObject.put("objectKey", objectKey);
        try{
            jsonObject = this.save(jsonObject, collectionName);
        }catch (Exception e){
            logger.error("save error: ", e);
        }
        return jsonObject;
    }




    public List<JSONObject> findAll(String collectionName){
        return mongoDBHelper.findAll(JSONObject.class, collectionName);
    }


    public JSONObject findById(String uid, String collectionName){
        return mongoDBHelper.findById(uid, JSONObject.class, collectionName);
    }
}
